package com.mate.cloud;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @description:    RocketMQ SDK同步消费消息测试
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/7/2 18:52
 * @updateUser:     MI
 * @updateTime:     2025/7/2 18:52
 * @updateRemark:   修改内容
 * @version:        1.0
 */
public class TransactionConsumer {
    public static void main(String[] args) throws MQClientException, InterruptedException {
        // 实例化消费者组名称
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("tx_consumer");
        // 指定name server地址
        defaultMQPushConsumer.setNamesrvAddr("192.168.110.17:9876");
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 订阅至少一个主题以供消费
        defaultMQPushConsumer.subscribe("order_tx_topic","*");
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                list.stream().forEach(message->{
                    //扣减库存
                    System.out.println("开始业务处理逻辑：消息体："+new String(message.getBody())+"->key:"+message.getKeys());
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; //签收
            }
        });
        defaultMQPushConsumer.start();
    }
}
